package com.yuji.aacar.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.yuji.aacar.R;
import com.yuji.aacar.base.BaseApplication;
import com.yuji.aacar.core.cores.utils.LogUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

/**
 * <li>Package: com.ttp.boss.service.DownloadService
 * <li>Author: shengshujie@126.com
 * <li>Date: 2017/3/29 17:13
 * <li>Discription: DownloadService 版本更新的下载类
 */
public class DownloadService extends Service {
    public static final String ACTION = "com.yuji.aacar.download";
    private static final int FINISH = 1;
    private static final int DOWNLOAD = 2;
    private static final int FAIL = 0;

    private String url;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    if (!TextUtils.isEmpty(url) && !TextUtils.isEmpty(path)) {
                        download(url);
                        break;
                    }
                }
            }
        }).start();
    }



    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LogUtil.e("onStartCommand", "--------------------");
        if (intent != null) {
            url = intent.getStringExtra("url");
            path = intent.getStringExtra("path");
            LogUtil.e("onStartCommand", url);
            LogUtil.e("onStartCommand", path);
        }
        return super.onStartCommand(intent, flags, startId);
    }

    private String path;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            LogUtil.e("handleMessage", msg.what);
            switch (msg.what) {
                case FINISH:
                    notification.flags = Notification.FLAG_AUTO_CANCEL;
                    notification.contentView.setTextViewText(R.id.download_tv, "下载完成");
                    notification.contentIntent = PendingIntent.getActivity(BaseApplication.application, 0, install(), PendingIntent.FLAG_UPDATE_CURRENT);
                    manager.notify(NOTIFICATION_ID, notification);
                    Toast.makeText(BaseApplication.appContext, "下载完成", Toast.LENGTH_LONG).show();
                    install();
                    stopSelf();
                    break;
                case 2:
                    notification.contentView.setTextViewText(R.id.progress_tv, msg.arg1 + "%");
                    notification.contentView.setProgressBar(R.id.progressbar_down, 100, msg.arg1, false);
                    manager.notify(NOTIFICATION_ID, notification);
                    break;
                case 0:
                    Toast.makeText(BaseApplication.appContext, "下载失败", Toast.LENGTH_LONG).show();
                    manager.cancel(NOTIFICATION_ID);
                    stopSelf();
                    break;
            }
        }
    };

    /**
     * 进度这里固定为100
     */
    public final int jd = 100;

    /**
     * @param urlStr http://f.txt
     */
    public void download(final String urlStr) {
        notifyView = new RemoteViews(BaseApplication.appContext.getPackageName(), R.layout.notify);
        new Thread(new Runnable() {
            @Override
            public void run() {
                File f = new File(path);
                if (f.exists()) {
                    f.delete();
                }
                InputStream is = null;
                OutputStream os = null;
                try {
                    // 构造URL
                    URL url = new URL(urlStr);
                    // 打开连接
                    URLConnection con = url.openConnection();
                    //获得文件的长度
                    int contentLength = con.getContentLength();
                    int cd = 0;
                    if (contentLength >= jd) {
                        cd = contentLength / jd;//计算出文件长度的1/100用于进度
                    }
                    // 输入流
                    is = con.getInputStream();
                    // 1K的数据缓冲
                    byte[] bs = new byte[1024];
                    // 读取到的数据长度
                    int len;
                    // 输出的文件流
                    os = new FileOutputStream(path);
                    // 开始读取
                    int i = 0;
                    int arg = 0;
                    while ((len = is.read(bs)) != -1) {
                        os.write(bs, 0, len);
                        i += len;
                        if (i >= cd) {
                            Message msg = Message.obtain();
                            msg.arg1 = ++arg;
                            msg.what = DOWNLOAD;
                            handler.sendMessage(msg);
                            i = 0;
                        }
                    }
                    Message msg = Message.obtain();
                    msg.arg1 = 100;
                    msg.what = DOWNLOAD;
                    handler.sendMessage(msg);
                    // 完毕，关闭所有链接
                    os.flush();
                    os.close();
                    is.close();
                    handler.sendEmptyMessage(FINISH);
                } catch (Exception e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(FAIL);
                }
            }
        }).start();
        initNotify();
    }

    private Notification notification;
    private NotificationManager manager;
    private RemoteViews notifyView;
    private final int NOTIFICATION_ID = 0x12;

    private void initNotify() {
        notification = new Notification();
        notification.icon = R.mipmap.logo;
        notification.flags |= Notification.FLAG_NO_CLEAR;

        // 通过RemoteViews 设置notification中View 的属性
        notification.contentView = notifyView;
        notification.contentView.setProgressBar(R.id.progressbar_down, 100, 0, false);
        notification.contentView.setTextViewText(R.id.progress_tv, "0%");
        notification.contentView.setTextViewText(R.id.download_tv, "正在下载，请稍后...");
        manager = (NotificationManager) BaseApplication.appContext.getSystemService(BaseApplication.appContext.NOTIFICATION_SERVICE);
        manager.notify(NOTIFICATION_ID, notification);
    }

    private Intent install() {
        // 核心是下面几句代码
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(new File(path)),
                "application/vnd.android.package-archive");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        BaseApplication.appContext.startActivity(intent);
        return intent;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        handler.removeMessages(0);
        handler.removeMessages(1);
        handler.removeMessages(2);
        stopSelf();
    }
}
